package com.furnitur.modules.portal.service.impl;


import com.furnitur.common.utils.SecurityUtils;
import com.furnitur.common.utils.ValidateUtils;
import com.furnitur.core.entity.user.User;
import com.furnitur.core.mapper.user.UserMapper;
import com.furnitur.core.service.UserService;
import com.furnitur.modules.portal.service.PortalUserService;
import com.furnitur.modules.portal.vo.user.PortalUserInfoVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

@Service
public class PortalUserServiceImpl implements PortalUserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserService userService;

    @Override
    public PortalUserInfoVO getCurrentUserInfo() {
        // 获取当前登录用户
        User currentUser = SecurityUtils.getCurrentUser();
        if (currentUser == null) {
           /* throw new BusinessException("用户未登录");*/
        }

        // 转换为VO
        PortalUserInfoVO userInfoVO = new PortalUserInfoVO();
        BeanUtils.copyProperties(currentUser, userInfoVO);
        
        return userInfoVO;
    }

    @Override
    public PortalUserInfoVO updateUserInfo(PortalUserInfoVO userInfo) {
        // 获取当前用户
        User currentUser = SecurityUtils.getCurrentUser();
        if (currentUser == null) {
            throw new RuntimeException("用户未登录");
        }

        // 参数验证
        if (userInfo == null) {
            throw new RuntimeException("更新信息不能为空");
        }

        // 验证手机号和邮箱格式
        if (!ValidateUtils.isValidPhone(userInfo.getPhone())) {
            throw new RuntimeException("手机号格式不正确");
        }
        if (!ValidateUtils.isValidEmail(userInfo.getEmail())) {
            throw new RuntimeException("邮箱格式不正确");
        }

        // 更新用户信息
        User user = new User();
        BeanUtils.copyProperties(userInfo, user);
        user.setId(currentUser.getId());
        
        // 更新数据库
        int rows = userMapper.updateById(user);
        if (rows != 1) {
            throw new RuntimeException("更新用户信息失败");
        }

        // 查询并返回最新的用户信息
        User updatedUser = userMapper.selectById(currentUser.getId());
        PortalUserInfoVO updatedInfo = new PortalUserInfoVO();
        BeanUtils.copyProperties(updatedUser, updatedInfo);
        
        return updatedInfo;
    }

    @Override
    public String uploadUserProfileImage(MultipartFile file) throws Exception {
        return userService.uploadUserProfileImage(file);
    }


} 